package com.cskaoyan.utils;


import org.hibernate.validator.internal.util.StringHelper;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author: thz
 * @class: IpUtil
 */

public class IpUtil {
    /**
     * 获取客户端Ip
     * @param request
     * @return
     */
    public static String getUserIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!StringHelper.isNullOrEmptyString(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (!StringHelper.isNullOrEmptyString(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
    /**
     * 获取服务端IP
     */
    public static String getServerIp(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forward-for");
        if(StringHelper.isNullOrEmptyString(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)){
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(StringHelper.isNullOrEmptyString(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)){
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(StringHelper.isNullOrEmptyString(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)){
            //根据网卡取本机配置IP
            InetAddress inetAddress = null;
            try {
                inetAddress = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
            }
            ipAddress = inetAddress.getHostAddress();

        }
        //对于通过多个代理的情况，第一个Ip为客户端实际IP，多个Ip按照“,”分隔
        if(StringHelper.isNullOrEmptyString(ipAddress) && ipAddress.length()>15){
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}
